import { _decorator, Component, Node, Input, math } from 'cc'
import { Constant } from '../framework/Constant'
import { GameManager } from '../framework/GameManager'

const { ccclass, property } = _decorator

@ccclass('UIMain')
export class UIMain extends Component {
  @property
  speed = 6.7
  @property(Node)
  planeBox: Node = null // 飞机总盒子
  @property(Node)
  plane: Node = null // 飞机本体
  @property(GameManager) // 游戏节点
  gameManager: GameManager = null

  rotZ = 0 // 飞机当前左右偏转角度
  maxRotZ = 60 // 飞机左右最大偏转角度
  rotSpeed = 5 // 飞机每次偏转角度

  start() {
    // 监听开始触摸
    this.node.on(Input.EventType.TOUCH_START, this.touchStart, this)
    // 监听触摸移动
    this.node.on(Input.EventType.TOUCH_MOVE, this.touchMove, this)
    // 监听结束触摸
    this.node.on(Input.EventType.TOUCH_END, this.touchEnd, this)
  }
  touchStart(event) {
    // 游戏状态判断
    switch (Constant.gameState) {
      // 0主界面
      case 0:
        this.gameManager.gameStart() // 开始游戏
        this.gameManager.switchEmit(true) // 玩家切换发射状态
        break
      // 1游戏中界面
      case 1:
        this.gameManager.switchEmit(true) // 玩家切换发射状态
        break
      // 2游戏结束界面
      case 2:
        break
      default:
        break
    }
  }
  touchMove(event) {
    // 游戏状态判断 1游戏中
    if (Constant.gameState === 1) {
      // event.getDelta() 获取本次位置和上次位置的差值
      const delta = event.getDelta()
      this.planeBoxMove(delta) // 飞机移动
      this.planeRotation(delta) // 飞机旋转
    }
  }
  touchEnd(event) {
    // 游戏状态判断 1游戏中
    if (Constant.gameState === 1) {
      this.gameManager.switchEmit(false) // 玩家切换发射状态
    }
    this.planeRotationOrigin()
  }
  // 飞机移动
  planeBoxMove(delta) {
    const speed = this.speed * 0.01
    const pos = this.planeBox.position
    let planeMoveX = pos.x + delta.x * speed
    let planeMoveZ = pos.z - delta.y * speed
    // 边界检测
    planeMoveX = this.valCorrection(planeMoveX, 24, -24)
    planeMoveZ = this.valCorrection(planeMoveZ, 50, -35)
    this.planeBox.setPosition(planeMoveX, pos.y, planeMoveZ)
  }
  // 飞机旋转
  planeRotation(delta) {
    delta.x > 0 ? (this.rotZ -= this.rotSpeed) : (this.rotZ += this.rotSpeed)
    // 边界检测
    this.rotZ = this.valCorrection(this.rotZ, this.maxRotZ, -this.maxRotZ)
    this.plane.setRotationFromEuler(0, 0, this.rotZ) // 设置飞机旋转角度
  }
  // 飞机旋转回归原位
  planeRotationOrigin() {
    this.schedule(this.callback, 0.02)
  }
  callback() {
    this.rotZ > 0 ? (this.rotZ -= this.rotSpeed) : (this.rotZ += this.rotSpeed)
    this.plane.setRotationFromEuler(0, 0, this.rotZ) // 设置飞机旋转角度
    if (this.rotZ === 0) this.unschedule(this.callback)
  }

  // 数据修正
  valCorrection(val: number, max: number, min: number): number {
    val = val > max ? max : val
    val = val < min ? min : val
    return val
  }
}
